#!/usr/local/bin/rake
# Copyright (C) 2003-2010 Wang Pengcheng <wpc0000@gmail.com>
# , released under the MIT license
# You may obtain a template of the MIT License at
# http://www.opensource.org/licenses/mit-license.php
$KCODE = 'u'

require 'erb'
require 'find'
require 'fileutils'

TMP='template/'
SRC='src/'
TEST='test/'
RAGEL='ragel/'
TEST_PREIX='Test'
ANT = 'ant'
DIST='dist/'
LIB='lib/'
PACKAGE_ROOT=''


desc 'Compile all files'
task :default => :dist

desc 'Ant project by default task'
task :dist do
  sh ANT
  Dir[TMP+'*.properties'].each do |f|
    FileUtils.cp(f,DIST+File.basename(f))
  end
  FileUtils.ln_s '../'+LIB,DIST+'lib' unless File.exists? DIST+'lib'
end

desc 'Ant run task'
task :run do
 sh ANT, 'run'
end

desc 'Ant test task'
task :test do
  Dir['*.sqlite'].each do |f|
    FileUtils.rm(f)
  end
  sh ANT, 'test'
end

desc 'Ragel ragel/files to src/'
task :ragel do
  rls = Dir[RAGEL+'*.rl']
  rls.each do |file|
    path = file.sub(RAGEL,SRC).gsub('.','/').sub('/rl','/java')
    system 'ragel', '-C','-o',path,file
  end
end

def tmptofile(tmp_path, file_path)
  if File.exist? file_path then
    puts 'Error: '+file_path+' EXISTS!'
    return
  end
  dir = file_path[0...(file_path.rindex('/'))]
  FileUtils.mkdir_p dir

  template = File.read(tmp_path)
  template = ERB.new(template)
  File.open(file_path,'w')do |nf|
    nf.puts template.result(binding)
  end
end

def getfilenames(filename)
  @filename=PACKAGE_ROOT+filename
  @filename=@filename.gsub('.','/')
  pkg = @filename.rindex('/')||0
  unless pkg==0
    @cc=@filename[(pkg+1)...(@filename.length)]
  else
    @cc=@filename[(pkg)...(@filename.length)]
  end

  unless pkg==0
    @filename = @filename[0..pkg]
    @package = @filename.gsub('/','.')[0...(@filename.length-1)]
  else
    @package = @filename = ''
  end
end

desc 'Make java source and test files with argument'
task :java,[:filename] do |t,args|
  args.with_default(:filename=> 'xxx')
  getfilenames args.filename
  files=[
    [ TMP+'template.java',SRC+@filename+@cc+'.java' ],
    [ TMP+'test_template.java',TEST+@filename+TEST_PREIX+@cc+'.java' ],
  ]
  files.each do |file|
    tmptofile(file[0],file[1])
  end
  puts 'Files '+@filename+@cc+' Created'

end

desc 'Delete source and test files'
task :rmjava,[:filename] do |t,args|
  args.with_default(:filename=> 'xxx')
  getfilenames args.filename
  files = [
    (SRC+@filename+@cc+'.java' ) ,
    (TEST+@filename+TEST_PREIX+@cc+'.java'),
  ]
  files.each do |file|
    FileUtils.rm(file) if File.exist? file
  end
  puts 'Files '+@filename+@cc+' deleted'
end

desc 'Delete temp files'
task :clean do
  FileUtils.rm(DIST+'lib') if File.exists? DIST+'lib'
  sh ANT, 'clean'
end
